package com.example.lenovo.asia5b.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.lenovo.asia5b.home.bean.UserBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.JsonTools2;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.SMSCode;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import app.BaseActivity;
import app.MyApplication;
import fay.frame.ui.U;

import static com.wushi.lenovo.asia5b.R.id.btn_verify_code_login;

/**
 * Created by lenovo on 2017/7/4.
 */

public class LoginForPhoneActivity extends BaseActivity implements ICallBack {

    private Intent intent = null;
    private TimeCount timeCount;
    private long timeOut;
    private String phone;
    private TextView loginPhoneNumView;
    private Button btn_verify_code;
    private EditText activity_login_phone_code;
    String url="",name="",openid="",type="";
    private LoadingDalog loadingDalog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_phone);

        initView();
    }

    private void initView(){
        loadingDalog = new LoadingDalog(this);
        loginPhoneNumView = (TextView)F.id(R.id.login_phone_num).getView();
        btn_verify_code = findViewById(R.id.btn_verify_code);
        activity_login_phone_code = findViewById(R.id.activity_login_phone_code);

        F.id(R.id.public_title_name).text(getResources().getString(R.string.SMS_login));
        F.id(R.id.tv_login_use_pwd).clicked(this);//帐号和密码登录
        F.id(R.id.btn_verify_code).clicked(this);//获取验证码
        F.id(btn_verify_code_login).clicked(this);//登录

        if (getIntent().hasExtra("url")) {
            url = getIntent().getStringExtra("url");
            name = getIntent().getStringExtra("name");
            openid = getIntent().getStringExtra("openid");
            type = getIntent().getStringExtra("type");
//            F.id(R.id.public_title_name).text(getResources().getString(R.string.app_name));
            F.id(R.id.public_title_name).text(getResources().getString(R.string.bdzh));
        }
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.tv_login_use_pwd://帐号和密码登录
                finish();
//                intent = new Intent(this,LoginActivity.class);
//                startActivityForResult(intent,300);
                break;
            case R.id.btn_verify_code://获取验证码
                phone = loginPhoneNumView.getText().toString();
                if(!TextUtils.isEmpty(phone)){
                    loadingDalog.show();
                    SMSCode.getCode(this,phone);
                }else{
                    U.Toast(this,getResources().getString(R.string.sjhbnwk)
                    );
                }
                break;
            case btn_verify_code_login://登录
                String code = activity_login_phone_code.getText().toString();
                if(!TextUtils.isEmpty(code)){
                    if(timeOut <= 1){
                        U.Toast(this,getResources().getString(R.string.yzmsx)
                        );
                    }else{
                        //判断用户是普通注册还是第三方注册
                        if (TextUtils.isEmpty(openid)) {
                            loginForPhone(code);
                        } else {
                            loginTwoForPhone(code);
                        }
                    }
                }else{
                    U.Toast(this,getResources().getString(R.string.yzmbnwk)
                    );
                }
                break;

        }
    }

    private void loginForPhone(String code){
        try{
            String phoneRUL = Setting.LOGINTOPHONE;
            Map<String,String> map = new HashMap<String,String>();
            map.put("phone",phone);
            map.put("code",code);

            Date date = new Date();
            String time = String.valueOf(date.getTime());
            map.put("time",time);

            String[] sortStr = {"phone"+phone,"code"+code,"time"+time,"user_alias"+ MyApplication.registrationId};
            map.put("user_alias",MyApplication.registrationId);
            String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(Logic.sortToString(sortStr)));
            map.put("sign",md5);
            Log.e("sign_md5","");
            JsonTools.getJsonAll(this,phoneRUL,map,1);
            JsonTools2.setOne(true);
            loadingDalog.show();
        }catch (Exception e){
            Log.e("短信登录接口error：",e.getMessage());
        }
    }

    /**
     * 第三方注册
     * @param code
     */
    private void loginTwoForPhone(String code){
        loadingDalog.show();
        try{
            String phoneRUL = Setting.THIRD_REG;
            Map<String,String> map = new HashMap<String,String>();
            map.put("uid",openid);
            map.put("third_user",name);
            map.put("third_type",type);
            map.put("code",code);
            map.put("phone",phone);
            map.put("img_url",url);
            map.put("user_alias",MyApplication.registrationId);
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            map.put("time",time);
            String[] sortStr = {"uid"+openid,"third_user"+name,"third_type"+type,"phone"+phone,"code"+code,"time"+time,"user_alias"+ MyApplication.registrationId};
            Log.e("参数为：：：：：：：：：",Logic.sortToString(sortStr));
            String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(Logic.sortToString(sortStr)));
            Log.e("图片地址为：：：：：：：：：",url);
            map.put("sign",md5);
            JsonTools.getJsonAll(this,phoneRUL,map,2);
        }catch (Exception e){
        }
    }
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            try{
                if(result != null && result instanceof JSONObject){
                    if(action == 0){
                        JSONObject jsonObject = (JSONObject)result;
                        String msgText = jsonObject.getString("MsgText");
                        if("true".equals(msgText)){
                            timeCount = new TimeCount(60000, 1000);
                            timeCount.start();
                        }else if("false".equals(msgText)){
                            String state = jsonObject.getString("State");
                            U.Toast(LoginForPhoneActivity.this,state);
                        }
                        loadingDalog.dismiss();
                    }else if(action == 1){
                        JSONObject jsonObject = (JSONObject)result;
                        int state = jsonObject.getInt("State");
                        if(state == 0){
                            JSONObject jsonUser = jsonObject.getJSONObject("user");
                            UserBean user = (UserBean)Logic.getBeanToJSONObject(jsonUser,new UserBean());
                            SharedPreferencesUtils.setObjectToShare(user,"user");
                            if(!TextUtils.isEmpty(user.user_name) && !TextUtils.isEmpty(user.mobile_phone)
                                    && !TextUtils.isEmpty(user.email)){
                                intent = new Intent(LoginForPhoneActivity.this,MainActivity.class);
                                finishAll();
                            }else{
                                intent = new Intent(LoginForPhoneActivity.this,UploadHeadPortraitActivity.class);
                                if (user.is_uname.equals("1")){
                                    intent.putExtra("phone",user.mobile_phone);
                                    intent.putExtra("register", "register");
                                }
                                intent.putExtra("user_id",user.user_id);
                                finish();
                            }
                            startActivity(intent);
                        }else if(state == 1){
                            U.Toast(LoginForPhoneActivity.this,getResources().getString(R.string.qmsb)
                            );
                        }else if(state == 2){
                            U.Toast(LoginForPhoneActivity.this,getResources().getString(R.string.sjyzmcw));
                        }else if(state == 3){
                            U.Toast(LoginForPhoneActivity.this,getResources().getString(R.string.gsjwzc));
                        }else if(state == 15){
                            U.Toast(LoginForPhoneActivity.this,getResources().getString(R.string.yzmsx));
                        }else if (state == 10) {
                            U.Toast(LoginForPhoneActivity.this,getResources().getString(R.string.hqyc));
                        }
                        loadingDalog.dismiss();
                    }
                    else if (action == 2) {
                        try {
                            JSONObject json = (JSONObject) result;
                            int state = (int)json.getInt("State");
                            if(state == 0) {
                                saveUser(json.getJSONObject("user"));
                            }
                            else if (state == 1) {
                                U.Toast(LoginForPhoneActivity.this, getResources().getString(R.string.qmsb));
                            } else if (state == 2) {
                                U.Toast(LoginForPhoneActivity.this, getResources().getString(R.string.cscw));
                            }else if (state == 10) {
                                U.Toast(LoginForPhoneActivity.this,getResources().getString(R.string.hqyc));
                            }
                        }catch (Exception e) {

                        }
                        loadingDalog.dismiss();

                    }
                }
            }catch (Exception e){
                Log.e("短信JSONError:d",e.getMessage());
            }
        }
    };


    @Override
    public void logicFinish(Object result, int action){
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 获取验证码倒计时
     */
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btn_verify_code.setClickable(false);
            timeOut = millisUntilFinished / 1000;
            btn_verify_code.setText(getResources().getString(R.string.message_has_been_sent)+"(" + timeOut + ")");
        }

        @Override
        public void onFinish() {
            btn_verify_code.setText(getResources().getString(R.string.to_obtain_the_verification_code));
            btn_verify_code.setClickable(true);
        }
    }


    /**
     * 登陆保存用户信息
     * @param json
     */
    private void saveUser(JSONObject json){
        try {
            UserBean bean = (UserBean)Logic.getBeanToJSONObject(json,new UserBean());
            SharedPreferencesUtils.setObjectToShare(bean,"user");
            Intent intent = null;
            if (bean.is_uname.equals("1")){
                intent = new Intent(this,UploadHeadPortraitActivity.class);
                intent.putExtra("phone",bean.mobile_phone);
                intent.putExtra("register", "register");
                intent.putExtra("user_id",bean.user_id);
                startActivity(intent);
                finish();
            } else {
                intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finishAll();
            }
        }catch (Exception e) {
            Log.e("111111111111111",e.toString());
        }
    }
}
